/**
 * @license
 * Copyright 2024 The Model Explorer Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ==============================================================================
 */

import {ErrorHandler, Injectable} from '@angular/core';

import {GaEventType, GaService} from './ga_service';

/**
 * Configures Angular error handling for Analytics tracking.
 */
@Injectable({providedIn: 'root'})
export class AppErrorHandler extends ErrorHandler {
  constructor(
    private readonly gaService: GaService,
    // This overrides the boq handler, so inject it here and call it ourselves.
    private readonly boqAngularErrorHandler: BoqAngularErrorHandler,
  ) {
    super();
  }

  override handleError(error: Error) {
    super.handleError(error); // Does this actually do anything?

    // 1st stack line is the context.
    const stack = error.stack?.split('\n');
    let context = stack?.shift() ?? '';
    context = stack?.shift()?.split('/').pop()?.split(')').shift() ?? context;
    // Context is the filename:line:column of the top item in the stack trace.

    // Track error in GA.
    this.gaService?.trackEvent(GaEventType.UI_ERROR, context, error.message);
  }
}
